﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Crossroad.System.User.Model;
using Crossroad.System.User.Service;
using Crossroad.System.User.Service.Impl;
using Crossroad.Utils.Extensions;
using Crossroad.Core.Helper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Crossroad.Core.Attributes;

namespace Crossroad.System.Api
{
    [EnableCors("custom")]
    [ApiResultFilter]
    [ApiController]
    public class BaseApi: ControllerBase
    {
        /// <summary>
        /// 用户应用service
        /// </summary>
        protected readonly UserAppService userAppService;

        public BaseApi()
        {
            userAppService = AutofacOption.Container.Resolve<IUserAppService>() as UserAppService;
        }

        public BaseApi(
            IUserAppService userAppServiceIpt
        )
        {
            userAppService = userAppServiceIpt as UserAppService;
        }


        /// <summary>
        /// 当前请求的 身份令牌
        /// </summary>
        protected string AccessToken => Request.Headers["Authorization"].FirstOrDefault();


        private UserApp _currentUserApp;
        /// <summary>
        /// 当前登录的用户APP
        /// </summary>
        protected UserApp CurrentUserApp
        {
            get
            {
                if (AccessToken.NotContent())
                    return null;

                if (_currentUserApp.NotNull())
                    return _currentUserApp;

                _currentUserApp = userAppService.GetUser(AccessToken);
                _currentUser = _currentUserApp.user;

                return _currentUserApp;
            }
        }


        private UserInfo _currentUser;
        /// <summary>
        /// 当前登录的用户
        /// </summary>
        protected UserInfo CurrentUser
        {
            get
            {
                if (AccessToken.NotContent())
                    return null;

                if (_currentUser != null)
                    return _currentUser;

                _currentUserApp = userAppService.GetUser(AccessToken);
                _currentUser = _currentUserApp.user;

                return _currentUser;
            }
        }


    }
}
